import { useState, useEffect, useCallback } from 'react';
import {
  Search,
  Filter,
  Download,
  Play,
  Trash2,
  RefreshCw,
  Video as VideoIcon,
  Plus,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  FileText,
  Eye,
} from 'lucide-react';
import type { Video } from '../types/video';
import { VideoStatus, VideoType } from '../types/video';
import videoService from '../services/videoService';
import VideoDetail from '../components/VideoDetail';
import VideoGenerate from '../components/VideoGenerate';
import VideoStatusTracker from '../components/VideoStatusTracker';
// import BatchVideoGenerate from '../components/BatchVideoGenerate';
import VideoPlayerModal from '../components/VideoPlayerModal';
import { toast } from '../stores/toastStore';
import { useApiError } from '../hooks/useApiError';
import { useConfirm } from '../hooks/useConfirm';
// HeyGenAccount imports removed - no longer needed for sync

export default function Videos() {
  const { handleError } = useApiError();
  const { confirmDelete, setLoading: setConfirmLoading, ConfirmComponent } = useConfirm();
  const [videos, setVideos] = useState<Video[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [filterType, setFilterType] = useState<string>('all');
  const [selectedVideos, setSelectedVideos] = useState<string[]>([]);
  const [syncing, setSyncing] = useState(false);
  const [showGenerateModal, setShowGenerateModal] = useState(false);
  // const [showBatchGenerateModal, setShowBatchGenerateModal] = useState(false);
  const [selectedVideoId, setSelectedVideoId] = useState<string | null>(null);
  const [showStatusTracker, setShowStatusTracker] = useState(false);
  const [statusVideoId, setStatusVideoId] = useState<string | null>(null);
  const [showVideoPlayer, setShowVideoPlayer] = useState(false);
  const [playerVideo, setPlayerVideo] = useState<Video | null>(null);
  const [stats, setStats] = useState({
    total: 0,
    completed: 0,
    processing: 0,
    failed: 0,
    draft: 0,
  });

  const loadVideos = useCallback(async () => {
    try {
      setLoading(true);
      const response = await videoService.getVideos();
      setVideos(response.videos || []);
    } catch (error) {
      handleError(error, '加载视频列表失败');
    } finally {
      setLoading(false);
    }
  }, [handleError]);

  const loadStats = useCallback(async () => {
    try {
      const statsData = await videoService.getVideoStats();
      setStats(statsData);
    } catch (error) {
      handleError(error, '加载统计数据失败');
    }
  }, [handleError]);

  useEffect(() => {
    loadVideos();
    loadStats();
  }, [loadVideos, loadStats]);

  const handleSync = async () => {
    try {
      setSyncing(true);
      await videoService.syncVideos(); // 使用新的同步方法，不需要传递账户ID
      await loadVideos();
      await loadStats();
    } catch (error) {
      handleError(error, '同步视频失败');
    } finally {
      setSyncing(false);
    }
  };

  const handleDeleteClick = async (video: Video) => {
    const confirmed = await confirmDelete(
      '您确定要删除这个视频吗？',
      video.video_title || video.video_id
    );

    if (!confirmed) return;

    try {
      setConfirmLoading(true);
      await videoService.deleteVideo(video.video_id);
      await loadVideos();
      toast.success('视频删除成功');
    } catch (error) {
      handleError(error, '删除视频失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  const handleBatchDeleteClick = async () => {
    if (selectedVideos.length === 0) return;

    const confirmed = await confirmDelete(
      `您确定要删除选中的 ${selectedVideos.length} 个视频吗？`,
      `将删除 ${selectedVideos.length} 个视频`
    );

    if (!confirmed) return;

    try {
      setConfirmLoading(true);
      await videoService.deleteVideos(selectedVideos);
      setSelectedVideos([]);
      await loadVideos();
      toast.success(`成功删除 ${selectedVideos.length} 个视频`);
    } catch (error) {
      handleError(error, '批量删除视频失败');
    } finally {
      setConfirmLoading(false);
    }
  };

  const handleBatchDownload = async () => {
    if (selectedVideos.length === 0) return;

    const selectedVideoObjects = videos.filter(
      v => selectedVideos.includes(v.video_id) && v.video_url && v.status === VideoStatus.COMPLETED
    );

    if (selectedVideoObjects.length === 0) {
      toast.warning('没有可下载的已完成视频');
      return;
    }

    try {
      toast.info(`开始批量下载 ${selectedVideoObjects.length} 个视频...`);

      for (let i = 0; i < selectedVideoObjects.length; i++) {
        const video = selectedVideoObjects[i];
        if (video.video_url) {
          try {
            // 直接使用签名链接触发浏览器下载/打开
            await downloadVideoFile(
              video.video_url,
              `${video.video_title || video.video_id}.mp4`,
              false
            );
            // 添加小延迟避免同时下载过多文件
            if (i < selectedVideoObjects.length - 1) {
              await new Promise(resolve => setTimeout(resolve, 500));
            }
          } catch (error) {
            console.error(`Failed to download video ${video.video_id}:`, error);
            // Keep individual download errors as console.error to avoid overwhelming user with many toasts
          }
        }
      }
      toast.success(`成功启动 ${selectedVideoObjects.length} 个视频的下载`);
    } catch (error) {
      handleError(error, '批量下载失败');
    }
  };

  const handleBatchRefresh = async () => {
    if (selectedVideos.length === 0) return;

    try {
      // 批量检查视频状态
      const promises = selectedVideos.map(async videoId => {
        try {
          await videoService.checkVideoStatusFromAPI(videoId);
        } catch (error) {
          console.error(`Failed to refresh status for video ${videoId}:`, error);
          // Keep individual refresh errors as console.error to avoid overwhelming user with many toasts
        }
      });

      await Promise.all(promises);
      await loadVideos(); // 重新加载视频列表
      toast.success(`已刷新 ${selectedVideos.length} 个视频的状态`);
    } catch (error) {
      handleError(error, '批量刷新状态失败');
    }
  };

  // 公共下载函数（避免跨域 fetch，直接打开签名链接）
  const downloadVideoFile = async (videoUrl: string, filename: string, showProgress = true) => {
    if (showProgress) {
      toast.info('开始下载视频，请稍候...');
    }

    const link = document.createElement('a');
    link.href = videoUrl;
    // download 对跨域可能被浏览器忽略，但仍会触发下载/打开
    link.download = filename;
    link.target = '_blank';
    link.rel = 'noopener noreferrer';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handleDownload = async (video: Video) => {
    if (!video.video_url) return;

    try {
      await downloadVideoFile(video.video_url, `${video.video_title || video.video_id}.mp4`, true);
      toast.success('视频下载已开始');
    } catch (error) {
      handleError(error, '视频下载失败');
    }
  };

  const handlePlayVideo = (video: Video) => {
    setPlayerVideo(video);
    setShowVideoPlayer(true);
  };

  const handleCloseVideoPlayer = () => {
    setShowVideoPlayer(false);
    setPlayerVideo(null);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case VideoStatus.COMPLETED:
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case VideoStatus.PROCESSING:
        return <Clock className="w-4 h-4 text-blue-500 animate-spin" />;
      case VideoStatus.FAILED:
        return <XCircle className="w-4 h-4 text-red-500" />;
      case VideoStatus.DRAFT:
        return <FileText className="w-4 h-4 text-gray-500" />;
      default:
        return <AlertCircle className="w-4 h-4 text-yellow-500" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const statusColors = {
      [VideoStatus.COMPLETED]: 'bg-green-900/30 border border-green-500/30 text-green-400',
      [VideoStatus.PROCESSING]: 'bg-blue-900/30 border border-blue-500/30 text-blue-400',
      [VideoStatus.FAILED]: 'bg-red-900/30 border border-red-500/30 text-red-400',
      [VideoStatus.DRAFT]: 'bg-gray-800/50 border border-gray-600/50 text-gray-300',
    };

    return (
      <span
        className={`px-2 py-1 text-xs font-medium rounded-full ${statusColors[status as VideoStatus] || 'bg-gray-800/50 border border-gray-600/50 text-gray-300'}`}
      >
        {status}
      </span>
    );
  };

  const getTypeBadge = (type: string) => {
    const typeColors = {
      [VideoType.GENERATED]: 'bg-purple-900/30 border border-purple-500/30 text-purple-400',
      [VideoType.TRANSLATED]: 'bg-indigo-900/30 border border-indigo-500/30 text-indigo-400',
    };

    return (
      <span
        className={`px-2 py-1 text-xs font-medium rounded-full ${typeColors[type as VideoType] || 'bg-gray-800/50 border border-gray-600/50 text-gray-300'}`}
      >
        {type}
      </span>
    );
  };

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const formatDate = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('zh-CN');
  };

  const handleCheckStatus = (videoId: string) => {
    setStatusVideoId(videoId);
    setShowStatusTracker(true);
  };

  const filteredVideos = videos.filter(video => {
    const matchesSearch =
      video.video_title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      video.video_id.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = filterStatus === 'all' || video.status === filterStatus;
    const matchesType = filterType === 'all' || video.type === filterType;

    return matchesSearch && matchesStatus && matchesType;
  });

  return (
    <div className="p-6">
      {/* Header */}
      <div className="mb-6">
        <div className="flex justify-between items-center mb-4">
          <h1 className="text-2xl font-bold text-gray-100">视频管理</h1>
          <div className="flex gap-2">
            <button
              onClick={() => setShowGenerateModal(true)}
              className="px-4 py-2 bg-cyan-600 text-white rounded-lg hover:bg-cyan-700 flex items-center gap-2 cursor-pointer transition-colors"
            >
              <Plus className="w-4 h-4" />
              生成视频
            </button>
            <button
              onClick={() => {
                /* setShowBatchGenerateModal(true) */
              }}
              disabled
              className="px-4 py-2 bg-gray-400 text-white rounded-lg cursor-not-allowed flex items-center gap-2"
              title="批量生成功能暂时禁用"
            >
              <VideoIcon className="w-4 h-4" />
              批量生成
            </button>
            <button
              onClick={handleSync}
              disabled={syncing}
              className="px-4 py-2 bg-gray-700 border border-gray-600 text-gray-100 rounded-lg hover:bg-gray-600 disabled:opacity-50 flex items-center gap-2 cursor-pointer disabled:cursor-not-allowed transition-colors"
            >
              <RefreshCw className={`w-4 h-4 ${syncing ? 'animate-spin' : ''}`} />
              同步视频
            </button>
          </div>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-5 gap-4 mb-6">
          <div className="bg-gray-900 border border-gray-800 p-4 rounded-lg hover:border-gray-700 transition-colors">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-400">总视频数</p>
                <p className="text-2xl font-bold text-gray-100">{stats.total}</p>
              </div>
              <div className="p-2 rounded-lg bg-gradient-to-br from-cyan-500 to-cyan-600">
                <VideoIcon className="w-6 h-6 text-white" />
              </div>
            </div>
          </div>
          <div className="bg-gray-900 border border-gray-800 p-4 rounded-lg hover:border-gray-700 transition-colors">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-400">已完成</p>
                <p className="text-2xl font-bold text-green-400">{stats.completed}</p>
              </div>
              <div className="p-2 rounded-lg bg-gradient-to-br from-green-500 to-green-600">
                <CheckCircle className="w-6 h-6 text-white" />
              </div>
            </div>
          </div>
          <div className="bg-gray-900 border border-gray-800 p-4 rounded-lg hover:border-gray-700 transition-colors">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-400">处理中</p>
                <p className="text-2xl font-bold text-blue-400">{stats.processing}</p>
              </div>
              <div className="p-2 rounded-lg bg-gradient-to-br from-blue-500 to-blue-600">
                <Clock className="w-6 h-6 text-white" />
              </div>
            </div>
          </div>
          <div className="bg-gray-900 border border-gray-800 p-4 rounded-lg hover:border-gray-700 transition-colors">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-400">失败</p>
                <p className="text-2xl font-bold text-red-400">{stats.failed}</p>
              </div>
              <div className="p-2 rounded-lg bg-gradient-to-br from-red-500 to-red-600">
                <XCircle className="w-6 h-6 text-white" />
              </div>
            </div>
          </div>
          <div className="bg-gray-900 border border-gray-800 p-4 rounded-lg hover:border-gray-700 transition-colors">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-400">草稿</p>
                <p className="text-2xl font-bold text-gray-100">{stats.draft}</p>
              </div>
              <div className="p-2 rounded-lg bg-gradient-to-br from-gray-500 to-gray-600">
                <FileText className="w-6 h-6 text-white" />
              </div>
            </div>
          </div>
        </div>

        {/* Filters */}
        <div className="bg-gray-900 border border-gray-800 p-4 rounded-lg">
          <div className="flex gap-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5" />
                <input
                  type="text"
                  placeholder="搜索视频标题或ID..."
                  value={searchTerm}
                  onChange={e => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:border-transparent text-gray-100 placeholder:text-gray-400"
                />
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Filter className="w-5 h-5 text-gray-400" />
              <select
                value={filterStatus}
                onChange={e => setFilterStatus(e.target.value)}
                className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 text-gray-100"
              >
                <option value="all">所有状态</option>
                <option value={VideoStatus.COMPLETED}>已完成</option>
                <option value={VideoStatus.PROCESSING}>处理中</option>
                <option value={VideoStatus.FAILED}>失败</option>
                <option value={VideoStatus.DRAFT}>草稿</option>
              </select>
              <select
                value={filterType}
                onChange={e => setFilterType(e.target.value)}
                className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-cyan-500 text-gray-100"
              >
                <option value="all">所有类型</option>
                <option value={VideoType.GENERATED}>生成</option>
                <option value={VideoType.TRANSLATED}>翻译</option>
              </select>
            </div>
            {selectedVideos.length > 0 && (
              <div className="flex gap-2">
                <button
                  onClick={handleBatchDownload}
                  className="px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2 cursor-pointer transition-colors text-sm"
                >
                  <Download className="w-4 h-4" />
                  下载选中 ({selectedVideos.length})
                </button>
                <button
                  onClick={handleBatchRefresh}
                  className="px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center gap-2 cursor-pointer transition-colors text-sm"
                >
                  <RefreshCw className="w-4 h-4" />
                  刷新状态
                </button>
                <button
                  onClick={handleBatchDeleteClick}
                  className="px-3 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 flex items-center gap-2 cursor-pointer transition-colors text-sm"
                >
                  <Trash2 className="w-4 h-4" />
                  删除选中 ({selectedVideos.length})
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Video List */}
      <div className="bg-gray-900 border border-gray-800 rounded-lg overflow-hidden">
        {loading ? (
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-cyan-500"></div>
          </div>
        ) : filteredVideos.length === 0 ? (
          <div className="text-center py-12">
            <VideoIcon className="w-12 h-12 text-gray-500 mx-auto mb-4" />
            <p className="text-gray-400">暂无视频</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-800 border-b border-gray-700">
                <tr>
                  <th className="px-4 py-3 text-left">
                    <input
                      type="checkbox"
                      checked={
                        selectedVideos.length === filteredVideos.length && filteredVideos.length > 0
                      }
                      onChange={e => {
                        if (e.target.checked) {
                          setSelectedVideos(filteredVideos.map(v => v.video_id));
                        } else {
                          setSelectedVideos([]);
                        }
                      }}
                      className="rounded bg-gray-700 border-gray-600 text-cyan-500 focus:ring-cyan-500"
                    />
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    预览
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    标题
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    状态
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    类型
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    时长
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    创建时间
                  </th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-800">
                {filteredVideos.map(video => (
                  <tr key={video.video_id} className="hover:bg-gray-800/50 transition-colors">
                    <td className="px-4 py-4">
                      <input
                        type="checkbox"
                        checked={selectedVideos.includes(video.video_id)}
                        onChange={e => {
                          if (e.target.checked) {
                            setSelectedVideos([...selectedVideos, video.video_id]);
                          } else {
                            setSelectedVideos(selectedVideos.filter(id => id !== video.video_id));
                          }
                        }}
                        className="rounded bg-gray-700 border-gray-600 text-cyan-500 focus:ring-cyan-500"
                      />
                    </td>
                    <td className="px-4 py-4">
                      <div className="w-20 h-20 relative bg-gray-800 border border-gray-700 rounded overflow-hidden">
                        {video.thumbnail_url ? (
                          <img
                            src={video.thumbnail_url}
                            alt={video.video_title}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <VideoIcon className="w-8 h-8 text-gray-500" />
                          </div>
                        )}
                        {video.status === VideoStatus.COMPLETED && video.video_url && (
                          <div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 hover:opacity-100 transition-opacity">
                            <Play className="w-8 h-8 text-white" />
                          </div>
                        )}
                      </div>
                    </td>
                    <td className="px-4 py-4">
                      <div>
                        <p className="font-medium text-gray-100">{video.video_title || '无标题'}</p>
                        <p className="text-xs text-gray-400">ID: {video.video_id}</p>
                      </div>
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-2">
                        {getStatusIcon(video.status)}
                        {getStatusBadge(video.status)}
                      </div>
                    </td>
                    <td className="px-4 py-4">{getTypeBadge(video.type)}</td>
                    <td className="px-4 py-4">
                      <span className="text-sm text-gray-300">
                        {video.duration > 0 ? formatDuration(video.duration) : '-'}
                      </span>
                    </td>
                    <td className="px-4 py-4">
                      <p className="text-sm text-gray-300">{formatDate(video.created_at)}</p>
                    </td>
                    <td className="px-4 py-4">
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => setSelectedVideoId(video.video_id)}
                          className="p-1 text-cyan-400 hover:text-cyan-300 cursor-pointer transition-colors"
                          title="查看详情"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleCheckStatus(video.video_id)}
                          className="p-1 text-orange-400 hover:text-orange-300 cursor-pointer transition-colors"
                          title="检查实时状态"
                        >
                          <RefreshCw className="w-4 h-4" />
                        </button>
                        {video.status === VideoStatus.COMPLETED && video.video_url && (
                          <>
                            <button
                              onClick={() => handlePlayVideo(video)}
                              className="p-1 text-blue-400 hover:text-blue-300 cursor-pointer transition-colors"
                              title="播放"
                            >
                              <Play className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleDownload(video)}
                              className="p-1 text-green-400 hover:text-green-300 cursor-pointer transition-colors"
                              title="下载"
                            >
                              <Download className="w-4 h-4" />
                            </button>
                          </>
                        )}
                        <button
                          onClick={() => handleDeleteClick(video)}
                          className="p-1 text-red-400 hover:text-red-300 cursor-pointer transition-colors"
                          title="删除"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Generate Video Modal */}
      {showGenerateModal && (
        <VideoGenerate
          onClose={() => setShowGenerateModal(false)}
          onSuccess={videoId => {
            console.log('Video generation started:', videoId);
            loadVideos(); // 刷新视频列表
          }}
        />
      )}

      {/* Video Detail Modal */}
      {selectedVideoId && (
        <VideoDetail videoId={selectedVideoId} onClose={() => setSelectedVideoId(null)} />
      )}

      {/* Video Status Tracker Modal */}
      {showStatusTracker && statusVideoId && (
        <VideoStatusTracker
          videoId={statusVideoId}
          onClose={() => {
            setShowStatusTracker(false);
            setStatusVideoId(null);
            loadVideos(); // 关闭时刷新视频列表以更新状态
          }}
        />
      )}

      {/* Batch Video Generate Modal - 暂时禁用 */}
      {/* {showBatchGenerateModal && (
        <BatchVideoGenerate
          onClose={() => setShowBatchGenerateModal(false)}
          onSuccess={() => {
            loadVideos(); // 刷新视频列表
          }}
        />
      )} */}

      {/* Video Player Modal */}
      {showVideoPlayer && playerVideo && playerVideo.video_url && (
        <VideoPlayerModal
          videoUrl={playerVideo.video_url}
          title={playerVideo.video_title || playerVideo.video_id}
          onClose={handleCloseVideoPlayer}
        />
      )}

      {/* Unified Confirm Dialog */}
      <ConfirmComponent />
    </div>
  );
}
